package com.jxwifi.cloud.quickclean.order;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.basicactivity.BasicActivity;
import com.idroid.utils.TextColorUtil;
import com.idroid.utils.TextDrawable;
import com.jxwifi.cloud.quickclean.address.AddressListActivity;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.app.PasswordLogin;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.bean.AddPreOrderResVoBean;
import com.jxwifi.cloud.quickclean.bean.HomeaddressBean;
import com.jxwifi.cloud.quickclean.bean.MyCleanersBean;
import com.jxwifi.cloud.quickclean.bean.ProductsBean;
import com.jxwifi.cloud.quickclean.orderdetails.OrderDetailsActivity;
import com.jxwifi.cloud.quickclean.pay.PayResult;
import com.jxwifi.cloud.quickclean.utils.AlterLocation;
import com.jxwifi.cloud.quickclean.utils.Constants;
import com.jxwifi.cloud.quickclean.utils.TitleClient;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;

/**
 * 订单确认
 * Created by Administrator on 2019/6/12.
 */

public class ConfirmOrderActivity extends ClientBasicActivity implements ConfirmOrderView {

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.tv_con_order_time)
    TextView mTvConOrderTime;
    @Bind(R.id.et_con_order_phone_name)
    EditText mTvConOrderPhoneName;
    @Bind(R.id.et_con_order_phone)
    EditText mEtConOrderPhone;
    @Bind(R.id.tv_con_order_type_leaflets)
    TextView mTvConOrderTypeLeaflets;
    @Bind(R.id.tv_con_order_remarks_text)
    TextView mTvConOrderRemarksText;
    @Bind(R.id.tv_confirm_order_price)
    TextView mTvConfirmOrderPrice;
    @Bind(R.id.tv_main_size_field)
    TextView mTvMainSizeField;//面积数据
    @Bind(R.id.tv_main_size_money)
    TextView mTvMainSizeMoney;//价格数据
    @Bind(R.id.tv_tk_address)
    TextView mTvTkAddress;//地址
    @Bind(R.id.tv_tk_confirm_address_details)
    TextView mTvTkConfirmAddressDetails;
    @Bind(R.id.tv_tk_confirm_modify)
    TextView mTvTkConfirmModify;
    @Bind(R.id.tv_collection_my_cleaner)
    TextView tv_collection_my_cleaner;
    @Bind(R.id.tv_unit_price_value)
    TextView tv_unit_price_value1;
    @Bind(R.id.rel_discount)
    RelativeLayout rel_discount;
    @Bind(R.id.tv_discount)
    TextView tv_discount;

    private ConfirmOrderPresenter mPresenter;
    private AddPreOrderResVoBean mAddpreOrderResVo;
    private ProductsBean mProudctBean;
    private int mProductPrice;//默认价格

    private String cleanerCode = "";//保洁员编号
    private String dispatchType;//(选填)派单类型:SYS 系统派单 Appoint：指定. 默认为SYS

    private String mWXPayCode;//微信支付接口返回的code
    private String mAddressType;
    private int mLimit = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        ButterKnife.bind(this);
        openEventBus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mAddpreOrderResVo = (AddPreOrderResVoBean) getIntent().getExtras().getSerializable("preorder_resvo");
        mProudctBean = (ProductsBean) getIntent().getExtras().getSerializable("preorder_products");
        //Log.i(TAG,"onCreate ==> getDefaultPrice = "+mProudctBean.getDefaultPrice()+" getServicePrice = "+mProudctBean.getServicePrice()+" DefaultPrice = "+mProudctBean.getDefaultPrice());
        //Log.i(TAG,"mAddpreOrderResVo ==> tips = "+mAddpreOrderResVo.getCustomerVipTips().isTips()+" tipsContent = "+mAddpreOrderResVo.getCustomerVipTips().getTipsContent());
        //mProductPrice=Integer.valueOf(getIntent().putExtra("preorder_pirce",0));
        mProductPrice=getIntent().getExtras().getInt("preorder_pirce",0);
        mPresenter = new ConfirmOrderPresenter(mBaseContext, this);
        initView();
    }

    public void initView() {
        dispatchType = StateUtils.SYS;
        mTvConOrderPhoneName.setText(mAddpreOrderResVo.getUserName());
        mEtConOrderPhone.setText(mAddpreOrderResVo.getUserTell());
        if(mAddpreOrderResVo.getCustomerVipTips().get(0).isTips()){
            rel_discount.setVisibility(View.VISIBLE);
            tv_discount.setText(mAddpreOrderResVo.getCustomerVipTips().get(0).getTipsContent());
        }
        onEstimate(mProductPrice);
        mPresenter.getOrderTime();
        mPresenter.initView();

    }

    @OnClick({R.id.rel_con_order_time, R.id.lin_con_order_mail, R.id.tv_con_order_my_cleaner, R.id.tv_con_order_explain, R.id.bt_con_order_button
            , R.id.rel_con_order_remarks, R.id.tv_con_order_type_leaflets, R.id.rel_size_field, R.id.rel_img_back_pressed,R.id.tv_confirm_details,R.id.tv_collection_my_cleaner,R.id.tv_tk_confirm_modify,R.id.rel_service_details})
    void clickCK(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            //时间选择
            case R.id.rel_con_order_time:
                mPresenter.TimeChoice();
                MobclickAgent.onEvent(this, "rel_con_order_time");
                break;
            //通讯录
            case R.id.lin_con_order_mail:
                if (isPermissionGranted(Manifest.permission.READ_CONTACTS,
                        Constants.READ_CONTACTS)) {
                    Intent intent1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent1, 0);
                    MobclickAgent.onEvent(this, "lin_con_order_mail");
                }
                break;
            //我的保洁员
            case R.id.tv_con_order_my_cleaner:
                if (LocationGaoDe.getLatitude()==0.0){
                    AlterLocation.popAlterDialog(mBaseContext, "定位服务已关闭", "请检查手机中定位是否开启");
                }else{
                    intent.setClass(mBaseContext, MyCleanerActivity.class);
                    intent.putExtra("order_code", mAddpreOrderResVo.getOrderCode());
                    intent.putExtra("service_time", mTvConOrderTime.getText().toString());
                    startActivity(intent);
                    MobclickAgent.onEvent(this, "tv_con_order_my_cleaner");
                }
                break;
            //收藏保洁员列表
            case R.id.tv_collection_my_cleaner:
                if (LocationGaoDe.getLatitude()==0.0){
                    AlterLocation.popAlterDialog(mBaseContext, "定位服务已关闭", "请检查手机中定位是否开启");
                }else{
                    intent.setClass(mBaseContext, MyCleanerActivity.class);
                    intent.putExtra("order_code", mAddpreOrderResVo.getOrderCode());
                    intent.putExtra("service_time", mTvConOrderTime.getText().toString());
                    intent.putExtra("isCollection", true);
                    startActivity(intent);
                    MobclickAgent.onEvent(this, "tv_con_order_my_cleaner");
                }
                break;
            //费用说明
            case R.id.tv_con_order_explain:
                mPresenter.priceDetail();
                MobclickAgent.onEvent(this, "tv_con_order_explain");
                break;
            //确认订单
            case R.id.bt_con_order_button:
                //确认订单弹框显示微信支付与支付宝支付选择操作
                mPresenter.ifPayDeposit();
                MobclickAgent.onEvent(this, "bt_con_order_button");
                break;
            //备注
            case R.id.rel_con_order_remarks:
                intent.setClass(mBaseContext, AddRemarksActivity.class);
                startActivity(intent);
                MobclickAgent.onEvent(this, "rel_con_order_remarks");
                break;
            //取消选中的保洁员
            case R.id.tv_con_order_type_leaflets:
                if (TextUtils.isEmpty(cleanerCode)) {

                    return;
                } else {
                    cleanerCode = "";
                    dispatchType = StateUtils.SYS;
                    mTvConOrderTypeLeaflets.setText("系统自动派单");
                    mTvConOrderTypeLeaflets.setBackgroundResource(0);
                    mTvConOrderTypeLeaflets.setCompoundDrawables(null, null, null, null);
                }
                break;
            //选择面积出发按钮
            case R.id.rel_size_field:
                mPresenter.MeasureService();
                MobclickAgent.onEvent(this, "rel_size_field");
                break;
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
                //服务详情
            case R.id.tv_confirm_details:
                mPresenter.ProductDetails();
                MobclickAgent.onEvent(this, "tv_confirm_details");
                break;
            //修改地址
            case R.id.tv_tk_confirm_modify:
                intent.setClass(mBaseContext, AddressListActivity.class);
                startActivity(intent);
                MobclickAgent.onEvent(mBaseContext, "tv_tk_confirm_modify");
                break;
            case R.id.rel_service_details:
                mPresenter.ProductDetails();
                MobclickAgent.onEvent(this, "tv_confirm_details");
                break;
        }
    }

    @Override
    public int getProductPrice() {
        return mProductPrice;
    }

    @Override
    public void getWXPayCode(String mOutTradNo) {
        mWXPayCode=mOutTradNo;
    }

    @Override
    public ProductsBean getProductsBean() {
        return mProudctBean;
    }

    @Override
    public TextView getField() {
        return mTvMainSizeField;
    }

    @Override
    public TextView getMoney() {
        return mTvMainSizeMoney;
    }

    @Override
    public TextView getUnitPrice() {
        return tv_unit_price_value1;
    }

    @Override
    public String getCleaningCode() {
        return cleanerCode;
    }

    @Override
    public String getdispatchType() {
        return dispatchType;
    }

    @Override
    public AddPreOrderResVoBean getResVoBean() {
        return mAddpreOrderResVo;
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public TextView getConOrderTime() {
        return mTvConOrderTime;
    }

    @Override
    public EditText getConOrderPhoneName() {
        return mTvConOrderPhoneName;
    }

    @Override
    public EditText getConOrderPhone() {
        return mEtConOrderPhone;
    }

    @Override
    public TextView getConOrderRemarksText() {
        return mTvConOrderRemarksText;
    }

    @Override
    public void onpriceDetail() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.priceDetail();
        }
    }

    @Override
    public void onProductDetails() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.ProductDetails();
        }
    }

    @Subscriber(tag = "e-mycleaner")
    private void getCondItion(MyCleanersBean mMyCleanersBean) {
        cleanerCode = mMyCleanersBean.getCleanerCode();
        //icon_delete_images
        mTvConOrderTypeLeaflets.setText(mMyCleanersBean.getRealName());
        mTvConOrderTypeLeaflets.setBackgroundResource(R.drawable.shap_my_cleaner_bg);
        TextDrawable.drawable(mBaseContext, mTvConOrderTypeLeaflets, R.mipmap.icon_delete_images, 2);
        dispatchType = StateUtils.APPOINT;
    }

    @Subscriber(tag = "e-addremarks")
    private void getRemarks(String remarks) {
        mTvConOrderRemarksText.setText(remarks);
    }

    public void onEstimate(int money) {
        String extimate = "预支订金：\u00A5" + money;
        //mEstimateMoney=money;
        SpannableString styledText = new SpannableString(extimate);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style3), 0, extimate.indexOf("\u00A5") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style2), extimate.indexOf("\u00A5") + 1, extimate.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvConfirmOrderPrice.setText(styledText);
    }

    @Subscriber(tag = "e-PayResult")
    private void getCondItion(PayResult mBean) {
        Toast toast = Toast.makeText(mBaseContext, "支付成功", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        if (!TextUtils.isEmpty(mBean.orderCode)) {
            Intent intent = new Intent();
            intent.setClass(mBaseContext, OrderDetailsActivity.class);
            intent.putExtra("order_code", mBean.orderCode);
            startActivity(intent);
            finish();
        }
    }

    @Subscriber(tag = "e-WXPayResult")
    private void getWXCondItion(PayResult mBean) {
        Toast toast = Toast.makeText(mBaseContext, "支付成功", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        if (!TextUtils.isEmpty(mWXPayCode)) {
            Intent intent = new Intent();
            intent.setClass(mBaseContext, OrderDetailsActivity.class);
            intent.putExtra("order_code", mWXPayCode);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LocationGaoDe.getLatitude()==0.0){
            new LocationGaoDe().init(getApplicationContext());
            LocationGaoDe.startLocation();
        }
        mPresenter.getinfo();
        if(AccountMgr.getGradeVip(mBaseContext).equals("V1")){
            mPresenter.getCollectionCleanerData();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                mTvConOrderPhoneName.setText(contacts[0]);
                mEtConOrderPhone.setText(contacts[1]);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象**
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标**
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名**
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码**
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = mBaseContext.checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }


    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        if (grantResults.length == 0) {
            return;
        }
        switch (requestCode) {
            case Constants.READ_CONTACTS:

                break;
            default:
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 0);
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }


    @Override
    public void onAddressBean(HomeaddressBean address) {
        if (address != null) {
            mTvTkAddress.setText(address.getProvince() + " " + address.getCity() + " " + address.getArea());
            mTvTkConfirmAddressDetails.setText(address.getAddress());
            mAddressType=StateUtils.MODIFY; //修改地址
            mTvTkConfirmModify.setText("修改地址");
        }else{
            mAddressType=StateUtils.ADD_TO;//添加地址
            mTvTkConfirmModify.setText("添加地址");
        }
    }

    @Override
    public void oninfo() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            //mPresenter.getinfo();
        }
    }

    @Override
    public String getServiceTime() {
        return mTvConOrderTime.getText().toString();
    }

    @Override
    public String getOrderCode() {
        return mAddpreOrderResVo.getOrderCode();
    }
    @Override
    public int getLimit() {
        return mLimit;
    }

    @Override
    public void setButtonGone() {
        tv_collection_my_cleaner.setVisibility(View.INVISIBLE);
    }
}
